<?php

namespace App\Http\Controllers;

use App\Models\ActivityProject;
use App\Models\Attachment;
use App\Models\BusinessPlanApply;
use App\Models\FundPlan;
use App\Models\MyMessage;
use App\Models\Notice;
use App\Models\ProjectAnswer;
use App\Models\ProjectFundPlan;
use App\Models\ProjectRecommendor;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Project;
use App\Models\Type;
use App\Models\Category;
use App\Models\User;
use App\Models\ProjectCategory;
use App\Models\Zone;
use App\Models\ProjectMember;
use App\Models\ProjectPhoto;
use App\Http\Requests\ProjectUpdateRequest;
use App\Http\Requests\ProjectInsertRequest;
use App\Http\Requests\ProjectMemberRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use DB;
use App\Http\Libs\Helper_Huanxin;

class ProjectController extends CommonController
{
    /**
     * 项目列表
     *
     * @return Response
     */
    public function getIndex()
    {
        $projects = Project::with('user', 'city')->orderBy('created_at', 'desc')->orderBy('recommend', 'desc')->paginate(10);

        return view('project/index')->with('projects', $projects)->with("actions", $this->actions);
    }

    public function search(Request $request)
    {

        $data = $request->input();
        $projects = Project::with('user', 'city')->orderBy('created_at', 'desc')->orderBy('recommend', 'desc');
        if (isset($data['subject']) && $data['subject'] != '') {
            $projects->where('subject', 'like', '%' . $data['subject'] . '%');
        }

        if (isset($data['create_user']) && $data['create_user'] != '') {
            $projects->whereIn('uid', function($query)use($data){
                $query->from('user')->where('nickname', 'like', '%' . $data['create_user'] . '%')->select('uid');
            });
        }

        if (isset($data['pStatus']) && $data['pStatus'] != '') {
            $projects->where('status', $data['pStatus']);
        }

        if (isset($data['type']) && $data['type'] != '') {
            $projects->where('type', $data['type']);
        }

        if (isset($data['roadshow']) && $data['roadshow'] != '') {
            $ids = ActivityProject::lists('project_id')->toArray();
            if(1==$data['roadshow']){
                $projects->whereIn('id', $ids);
            }
            if(0==$data['roadshow']){
                $projects->whereNotIn('id', $ids);
            }

        }

        $projects = $projects->paginate(10);

        return view('project.search')->with('projects', $projects)->with("actions", $this->actions);
//            ->with('track_person', $data['track_person'])
//            ->with('type', $data['type'])
//            ->with('subject', $data['subject'])
//            ->with('pStatus', $data['pStatus'])->with('roadshow', $data['roadshow']);
    }

    /**
     * 批量审核项目
     */
    public function postMassAudit(Request $request)
    {
        $data = $request->input();
        if ($data['status'] == null) {
            return AjaxCallbackMessage('请选择审核状态', false);
        }

        if ($data['project'] == null) {
            return AjaxCallbackMessage('至少要选择一个待审核的项目', false);
        }

        $projects = $this->explode($data['project']);

        $result = Project::whereIn('id', $projects)->update(['status' => $data['status']]);

        if ($result) {
            return AjaxCallbackMessage('成功审核' . $result . '条项目', true, url('project/index'));
        } else {
            return AjaxCallbackMessage('审核失败，请联系管理员', false);
        }
    }

    private function explode($data)
    {
        $projectStr = explode(",", $data);
        $projects = [];
        foreach ($projectStr as $v) {
            if (is_numeric($v)) {
                $projects[] = $v;
            }
        }

        return $projects;
    }

    /**
     * 查看项目详情
     *
     * @return Response
     */
    public function getDetail(Request $request)
    {
        $project_id = $request->input('id');
        $project = Project::where('id', $project_id)->first();
        $project_categories = $project->categories()->lists('id');
        $categories = Category::all()->lists('name', 'id');
        $users = User::all()->lists('nickname', 'uid');

        //投资阶段
        $invest_period = Type::with('type')->whereHas(
            'type',
            function ($q) {
                $q->where('code', 'invest_period');
            }
        )->lists('name', 'code');

        //项目阶段
        $project_period = Type::with('type')->whereHas(
            'type',
            function ($q) {
                $q->where('code', 'project_period');
            }
        )->lists('name', 'code');

        $data = array(
            'project'            => $project,
            'categories'         => $categories,
            'project_categories' => $project_categories,
            'users'              => $users,
            'invest_period'      => $invest_period,
            'project_period'     => $project_period,
        );

        return view('project/detail', $data);
    }

    /**
     * 项目编辑处理
     *
     * @param  int $id
     * @return Response
     */
    public function postUpdate(ProjectUpdateRequest $request)
    {
        $data = $request->input();

        if(isset($data['type']) ){
            if('newthree'!=$data['type'] && 'chuangye'!=$data['type']&& 'ppp'!=$data['type']){
                return AjaxCallbackMessage('项目类型只能为创业、新三板或ppp', false);
            }

            if(3==$data['status']&& 'newthree'==$data['type']){
                return AjaxCallbackMessage('新三板项目不能够选择融资成功选项', false);
            }
        }

        array_pull($data, '_token');
        if (isset($data['pubdate'])) {
            $data['pubdate'] = strtotime($data['pubdate']);
        }

        if (isset($data['start_time'])) {
            $data['start_time'] = strtotime($data['start_time']);
        }
        if (isset($data['invest_way'])) {
            $data['invest_way'] = implode(',', $data['invest_way']);
        }

        if (isset($data['out'])) {
            $data['out'] = implode(',', $data['out']);
        }

        $categories = array_pull($data, 'categories');

        if (isset($data['plans'])) {
            $plans = array_pull($data, 'plans');
        }

        $project = Project::find($data['id']);
        $project->categories()->detach();
        $project->categories()->attach($categories);

        $project->plans()->detach();
        if (isset($plans)) {
            $project->plans()->attach($plans);
        }

        if (isset($data['bp_name'])&& $data['bp_name'] != '' && $data['bp'] != '') {
            if ($project->business_plan > 0) {
                $bp = Attachment::find($project->business_plan);
                if ($bp->url != $data['bp']) {
                    //删除原来的bp记录
                    Attachment::where('id', $project->business_plan)->delete();
                    //添加新的记录
                    $attach = Attachment::create(
                        ['filename' => $data['bp_name'], 'filetype' => $data['bp_filetype'], 'filesize' => $data['bp_filesize'] , 'url' => $data['bp']]
                    );
                    Project::where('id', $data['id'])->update(['business_plan' => $attach->id]);
                } else {
                    //更新原来的记录
                    Attachment::where('id', $project->business_plan)->update(
                        ['filename' => $data['bp_name'], 'filetype' => $data['bp_filetype'], 'filesize' => $data['bp_filesize'] , 'url' => $data['bp']]
                    );
                }
            } else {
                //以前没有计划书，现在上传了计划书。
                $attach = Attachment::create(
                    ['filename' => $data['bp_name'], 'filetype' => $data['bp_filetype'], 'filesize' => $data['bp_filesize'], 'url' => $data['bp']]
                );
                Project::where('id', $data['id'])->update(['business_plan' => $attach->id]);
                //给那些订阅了的人发送环信
                $uids = BusinessPlanApply::where('project_id', $data['id'])->lists('uid');
                $url = $this->wjtrUrl .'webapp/project/detail?pagetag=01-19&id='.$data['id'] ;
//                @Helper_Huanxin::sendMessage(
//                    $uids,
//                    '你申请查阅的项目商业计划书已添加。项目名称：' . $project->subject . '，请点击查阅。',
//                    $from = "admin",
//                    $ext = array(
//                        'type'    => "hyperjump",
//                        'content' => array(array('hyper' => '请点击查阅', 'text' => $url))
//                    )
//                );
            }
        }

        unset($data['city_id'], $data['user_search'], $data['bp'], $data['bp_name'], $data['bp_filetype'], $data['bp_filesize'] );

        if(isset($data['type']) && 'newthree'==$data['type']){
            $data['project_period'] = $data['invest_way'] ='';
        }
        $old = Project::where('id', $data['id'])->first();

        $result = Project::where('id', $data['id'])->update($data);
        $new = Project::where('id', $data['id'])->first();


        /***调用app接口刷新缓存***/
        $url = $this->wjtrUrl . "script/cache/refreshprojectlist";
        $post = array();
        @curl($url, $post);
        //审核通过，并且和原来的状态不同，则发送一条信息
//        if ($data['status'] == 1 && $old->status != 1) {
//            Notice::create(['title' => '您的项目已通过审核，应邀参加无界路演', 'content' => trans('webNotice.projectSuccess.content', ['project' => $old->subject]), 'type' => 1, 'uid' => $data['uid']]);
//        }


        if ($data['status'] == 1 && $old->status != 1) {
            if('newthree' == $new->type){
                $m_title = '恭喜您，发布的新三板项目已经成功发布';
                $m_content = '无界投融，一站式投融资服务平台，为你提供全方位的项目路演保障。你的新三板项目已通过系统审核，在无界投融成功发布。';
                $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>项目名称：<span class="orange">'.$new->subject.'</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
                $m_end='<p>特别说明，新三板项目的每次编辑都将需要审核，如给你带来不便，请谅解。</p>';

                MyMessage::createMessage($new->uid,$m_title,'official',$m_content,$m_ext,$m_end);
            }elseif('ppp' == $new->type){
                $m_title = '恭喜,您申请的PPP项目已经成功发布';
                $m_content = '无界投融，一站式投融资服务平台，为你提供全方位的项目路演保障。你的PPP项目已通过系统审核，在无界投融成功发布。';
                $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>项目名称：<span class="orange">'.$new->subject.'</span></p>
	                            </div>
	                            <div class="borderLine"></div>';
                $m_end='<p>特别说明，PPP项目的每次编辑都将需要审核，如给您带来不便，敬请谅解。</p>';


                MyMessage::createMessage($new->uid,$m_title,'official',$m_content,$m_ext,$m_end);
                $content_sms=trans('sms.pppproject',array('subject'=>$new->subject));
                $user=User::where('uid',$new->uid)->first();
                @SendSMS($user->username,$content_sms,'pppproject',3);
            }
        }elseif($data['status'] == 2 && $old->status != 2) {
            if('newthree' == $new->type){
                $m_title = '很抱歉您发布的新三板项目没有成功';
                $m_content = '无界投融，一站式投融资服务平台，为你提供全方位的项目路演保障。你的新三板项目未通过系统审核，不能在无界投融发布。';
                $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>失败原因：所提交的资料补完整或存在疑问。</p>
	                            </div>
	                            <div class="borderLine"></div>';
                $m_end='<p>特别说明，新三板项目的每次编辑都将需要审核，如给你带来不便，请谅解。</p>';

                MyMessage::createMessage($new->uid,$m_title,'official',$m_content,$m_ext,$m_end);
            }elseif('ppp' == $new->type){
                $m_title = '很抱歉您的PPP项目发布没有成功';
                $m_content = '无界投融，一站式投融资服务平台，为你提供全方位的项目路演保障。你的PPP项目未通过系统审核，不能在无界投融发布。';
                $m_ext='<div class="mt10 mb10 dark2_gray">
                                <p>失败原因：所提交的资料补完整或存在疑问。</p>
	                            </div>
	                            <div class="borderLine"></div>';
                $m_end='<p>特别说明，每个PPP项目都会有专人电话对接，核实项目情况后才能发布，如给您带来不便，敬请谅解。</p>';

                MyMessage::createMessage($new->uid,$m_title,'official',$m_content,$m_ext,$m_end);
            }
        }

            return AjaxCallbackMessage('项目编辑成功', true, url('project/index'));
    }

    /**
     * 编辑项目基本详情
     *
     * @return Response
     */
    public function getEdit(Request $request)
    {
        //
        $project_id = $request->input('id');
        $project = Project::where('id', $project_id)->first();
        $project_categories = $project->categories()->lists('id');
        $categories = Category::all()->lists('name', 'id');
        $users = User::all();
        $zones = Zone::cache(1);
        $zoneTree = toTree($zones, 'id', 'upid', 'children');
        $family = familyTree($zones, $project->zone_id);
        $bp = '';
        if (isset($project->business_plan) && $project->business_plan > 0) {
            $bp = Attachment::where('id', $project->business_plan)->first();
        }
        $plans = FundPlan::get();


        $plan_ids = ProjectFundPlan::where('project_id', $project_id)->lists('fund_plan_id')->toArray();
        if ($project->type == 'chuangye') {
            //投资阶段
            $invest_period = Type::with('type')->whereHas(
                'type',
                function ($q) {
                    $q->where('code', 'invest_period');
                }
            )->get();

            //项目阶段
            $project_period = Type::with('type')->whereHas(
                'type',
                function ($q) {
                    $q->where('code', 'project_period');
                }
            )->get();

            $data = array(
                'project'            => $project,
                'categories'         => $categories,
                'plans'         => $plans,
                'plan_ids'         => $plan_ids,
                'project_categories' => $project_categories,
                'users'              => $users,
                'zoneTree'           => $zoneTree,
                'family'             => $family,
                'invest_period'      => $invest_period,
                'project_period'     => $project_period,
                'bp'                 => $bp,
            );

            return view('project/editchuangye', $data);
        } elseif($project->type == 'newthree') {
            $data = array(
                'project'            => $project,
                'categories'         => $categories,
                'project_categories' => $project_categories,
                'users'              => $users,
                'zoneTree'           => $zoneTree,
                'family'             => $family,
                'bp'                 => $bp,
                'plans'         => $plans,
                'plan_ids'         => $plan_ids,
            );

            return view('project/editnewthree', $data);
        }elseif($project->type == 'ppp') {
            $data = array(
                'project'            => $project,
                'categories'         => $categories,
                'project_categories' => $project_categories,

            );

            return view('project/editppp', $data);
        }
    }

    /**
     * 获取创建项目时的种类选择页面
     */
    public function  getTypeSelect()
    {
        return view('project.typeselect');
    }

    public function postSelect(Request $request)
    {
        $this->validate($request, ['type' => 'required|in:chuangye,newthree,ppp']);

        $data = $request->input();
        $categories = Category::all()->lists('name', 'id');
        $users = User::all();
        $zoneTree = Zone::all();
        $plans = FundPlan::get();

        if ($data['type'] == 'chuangye') {
            //投资阶段
            $invest_period = Type::with('type')->whereHas(
                'type',
                function ($q) {
                    $q->where('code', 'invest_period');
                }
            )->get();

            //项目阶段
            $project_period = Type::with('type')->whereHas(
                'type',
                function ($q) {
                    $q->where('code', 'project_period');
                }
            )->get();

            $data = array(
                'categories'     => $categories,
                'users'          => $users,
                'zoneTree'       => $zoneTree,
                'invest_period'  => $invest_period,
                'project_period' => $project_period,
                'plans' => $plans,
            );

            return view('project/createchuangye', $data);
        } elseif($data['type'] == 'newthree') {
            $data = array(
                'categories' => $categories,
                'users'      => $users,
                'plans' => $plans,
                'zoneTree'   => $zoneTree
            );

            return view('project/createnewthree', $data);
        }elseif($data['type'] == 'ppp') {
            $data = array(
                'categories' => $categories,
                'users'      => $users,
                'zoneTree'   => $zoneTree
            );

            return view('project/createppp', $data);
        }
    }

    /**
     * 插入项目信息
     *
     * @param  int $id
     * @return Response
     */
    public function postInsert(ProjectInsertRequest $request)
    {
        //
        $data = $request->input();

        //如果上传了商业计划书,就先保存
        if (isset($data['bp_name']) && $data['bp_name'] != '' && $data['bp'] != '') {
            $attach = Attachment::create(
                ['filename' => $data['bp_name'], 'filetype' => $data['bp_filetype'], 'filesize' => $data['bp_filesize'],  'url' => $data['bp']]
            );
        }

        unset($data['user_search'], $data['bp'], $data['bp_name'], $data['bp_filetype'], $data['bp_filesize']);
        if (isset($data['pubdate'])) {
            $data['pubdate'] = strtotime($data['pubdate']);
        }

        if (isset($data['start_time'])) {
            $data['start_time'] = strtotime($data['start_time']);
        }
        if (isset($data['invest_way'])) {
            $data['invest_way'] = implode(',', $data['invest_way']);
        }

        //取出关联数据
        $categories = array_pull($data, 'categories');
        if (isset($data['plans'])) {
            $plans = array_pull($data, 'plans');
        }

        if (isset($data['out'])) {
            $data['out'] = implode(',', $data['out']);
        }

        //如果是创业项目就不用审核
        if (isset($data['type']) && 'chuangye' == $data['type']) {
            $data['status'] = 1;
        }

        $project = Project::create($data);

        //插入关联数据
        $project_id = $project->id;
        $project = Project::find($project_id);
        $project->categories()->attach($categories);
        if (isset($plans)) {
            $project->plans()->attach($plans);
        }

        //如果上传bp，则把bp的id，同步过来
        if (isset($attach->id) && 0 != $attach->id) {
            Project::where('id', $project_id)->update(['business_plan' => $attach->id]);
        }

        if ($project) {
            return AjaxCallbackMessage('项目新增成功', true, url('project/index'));
        } else {
            return AjaxCallbackMessage('项目新增失败', false, url('project/index'));
        }
    }


    /**
     * 获取推荐方列表页面
     */
    public function getRecommend(Request $request)
    {
        $data = $request->input();
        $lists = ProjectRecommendor::where('project_id', $data['id'])->paginate(10);

        return view('project/recommend')->with('lists', $lists)->with('id', $data['id'])->with('actions', $this->actions);
    }

    /**
     * 获取推荐方创建页面
     */
    public function getCreateRec(Request $request)
    {
        $data = $request->input();

        return view('project/createrec')->with('project_id', $data['id']);
    }

    /**
     * 执行一个推荐方创建
     */
    public function postCreateRec(Request $request)
    {
        $data = $request->input();
        $project_id = $data['project_id'];

        unset($data['user_search'], $data['type'], $data['formType'], $data['_token']);

        ProjectRecommendor::create($data);

        return AjaxCallbackMessage('创建成功', true, url('project/recommend?id=' . $project_id));
    }

    /**
     *获取推荐方编辑页面
     */
    public function getEditRec(Request $request)
    {
        $data = $request->input();
        $list = ProjectRecommendor::where('id', $data['id'])->first();

        return view('project/editrec')->with('list', $list);
    }

    /**
     * 执行一个编辑
     */
    public function postEditRec(Request $request)
    {
        $data = $request->input();

        $project_id = $data['project_id'];

        unset($data['user_search'], $data['type'], $data['formType'], $data['_token'], $data['project_id']);

        ProjectRecommendor::where('id', $data['id'])->update($data);

        return AjaxCallbackMessage('编辑成功', true, url('project/recommend?id=' . $project_id));
    }

    public function postDelRec(Request $request)
    {
        $data = $request->input();

        ProjectRecommendor::where('id', $data['pid'])->delete();

        return AjaxCallbackMessage('删除成功', true);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return Response
     */
    public function postDelete(Request $request)
    {
        //
        $id = $request->input('pid');
        $projectAnswer = ProjectAnswer::where('project_id', $id)->get();
        if (count($projectAnswer)) {
            return AjaxCallbackMessage('该项目存在投资者六问的答案，不能直接删除', false);
        }

        $result = Project::where('id', $id)->delete();
        ProjectCategory::where('project_id', $id)->delete();
        ProjectMember::where('project_id', $id)->delete();
        ProjectPhoto::where('project_id', $id)->delete();

        if ($result) {
//            return $this->tip('项目删除成功', url('project/index'), true);
            return AjaxCallbackMessage('项目删除成功', true, url('project/index'));
        } else {
            return AjaxCallbackMessage('项目删除失败', false);
        }
    }

    /**
     * 查看项目详情
     *
     * @return Response
     */
    public function getInfo(Request $request)
    {

        $project_id = $request->input('id');

        return view('project/info', array('project_id' => $project_id));
    }

    /**
     * 查看项目成员
     *
     * @return Response
     */
    public function getMember(Request $request)
    {

        $project_id = $request->input('id');
        $project = Project::find($project_id);
        $members = $project->members()->paginate(10);

        $data = array(
            'project_id' => $project_id,
            'members'    => $members,
        );

        return view('project/member/index', $data);
    }

    /**
     * 编辑项目成员
     *
     * @return Response
     */
    public function getMemberedit(Request $request)
    {

        $member_id = $request->input('id');
        $member = ProjectMember::find($member_id);

        $data = array(
            'member' => $member,
        );

        return view('project/member/edit', $data);
    }

    /**
     * 新增项目成员
     *
     * @return Response
     */
    public function getMembercreate(Request $request)
    {

        $project_id = $request->input('id');

        $data = array(
            'project_id' => $project_id,
        );

        return view('project/member/create', $data);
    }

    /**
     * 插入项目成员
     *
     * @return Response
     */
    public function postMemberinsert(ProjectMemberRequest $request)
    {

        $data = $request->input();

        $nowLeader = ProjectMember::where('project_id', $data['project_id'])->where('is_leader', 1)->get();

        if ($data['is_leader'] == 1 && count($nowLeader)) {
            return AjaxCallbackMessage('成员新增失败,一个项目中不应该有两个领导', false);
        }
        $result = ProjectMember::create($data);

        if ($result) {
            return AjaxCallbackMessage('成员新增成功', true, url('project/member?id=' . $data['project_id']));
        } else {
            return AjaxCallbackMessage('成员新增失败', false);
        }
    }

    /**
     * 项目成员信息更新
     *
     * @return Response
     */
    public function postMemberupdate(Request $request)
    {
        $data = $request->input();

        $nowLeader = ProjectMember::where('project_id', $data['project_id'])
            ->where('is_leader', 1)->where('id', '<>', $data['id'])
            ->get();

        if ($data['is_leader'] == 1 && count($nowLeader)) {
            return AjaxCallbackMessage('项目成员编辑失败,一个项目中不应该有两个领导', false);
        }
        unset($data['post_key']);

        $result = ProjectMember::where('id', $data['id'])->update($data);

        if ($result) {
            return AjaxCallbackMessage('项目成员编辑成功', true, url('project/member?id=' . $data['project_id']));
        } else {
            return AjaxCallbackMessage('项目成员编辑失败', false);
        }
    }

    /**
     * 删除项目成员
     *
     * @param  int $id
     * @return Response
     */
    public function postMemberdelete(Request $request)
    {
        //
        $id = $request->input('mid');
        $member = ProjectMember::find($id);
        $member->delete();

        return AjaxCallbackMessage('项目成员删除成功', true, url('project/member?id=' . $member->project_id));
    }

    /**
     * 查看项目被收藏情况
     *
     * @return Response
     */
    public function getFavourite(Request $request)
    {
        $project_id = $request->input('id');
        $project = Project::find($project_id);
//        dd($project);
        $favourites = $project->favourite()->with('user')->where('model', 'project')->paginate(10);

        $data = array(
            'project_id' => $project_id,
            'project'    => $project,
            'favourites' => $favourites,
        );

        return view('project/favourite/index', $data);
    }

    /**
     * 查看项目六问
     *
     * @return Response
     */
    public function getQuestion(Request $request)
    {

        $project_id = $request->input('id');
        $project = Project::find($project_id);
        $answers = $project->answers()->with('question')->get();

        $data = array(
            'project_id' => $project_id,
            'project'    => $project,
            'answers'    => $answers,
        );

        return view('project/question/index', $data);
    }

    /**
     * 查看项目图片
     *
     * @return Response
     */
    public function getPhoto(Request $request)
    {

        $project_id = $request->input('id');
        $project = Project::find($project_id);
        $photos = $project->photos()->with('user')->paginate(10);

        $data = array(
            'project_id' => $project_id,
            'project'    => $project,
            'photos'     => $photos,
        );

        return view('project/photo/index', $data);
    }

    /**
     * 编辑项目图片
     *
     * @return Response
     */
    public function getPhotoedit(Request $request)
    {
        //
        $photo_id = $request->input('id');
        $photo = ProjectPhoto::where('id', $photo_id)->first();
        $type = Type::cache();
        $phototype = $type['project_image_type'];
        $data = array(
            'photo'     => $photo,
            'phototype' => $phototype,
        );

        return view('project/photo/edit', $data);
    }

    /**
     * 更新项目图片
     *
     * @return Response
     */
    public function postPhotoupdate(Request $request)
    {
        $data = $request->input();
        $result = ProjectPhoto::where('id', $data['id'])->update($data);

        if ($result) {
            return AjaxCallbackMessage('项目图片更新成功', true, url('project/photo?id=' . $data['project_id']));
        } else {
            return AjaxCallbackMessage('项目图片更新失败', false, url('project/photo?id=' . $data['project_id']));
        }
    }

    /**
     * 新增图片
     *
     * @return Response
     */
    public function getPhotocreate(Request $request)
    {

        $project_id = $request->input('id');
        $type = Type::cache();
        $phototype = $type['project_image_type'];
        $users = User::all();

        $data = array(
            'project_id' => $project_id,
            'phototype'  => $phototype,
            'users'      => $users,
        );

        return view('project/photo/create', $data);
    }

    /**
     * 插入项目图片
     *
     * @return Response
     */
    public function postPhotoinsert(Request $request)
    {

        $data = $request->input();
        /*$project_id = array_pull($data,'project_id');*/
        unset($data['user_search']);

        $result = ProjectPhoto::create($data);
        if ($result) {
            return AjaxCallbackMessage('项目图片新增成功', true, url('project/photo?id=' . $data['project_id']));
        } else {
            return AjaxCallbackMessage('项目图片新增失败', false, url('project/photo?id=' . $data['project_id']));
        }
    }

    /**
     * 删除项目图片
     *
     * @return Response
     */
    public function postPhotodelete(Request $request)
    {

        $project_photo_id = $request->input('pid');

        $photo = ProjectPhoto::find($project_photo_id);

        $result = ProjectPhoto::destroy($project_photo_id);

        if ($result) {
//            return $this->tip('项目图片删除成功', url('project/photo?id=' . $photo['project_id']), true);
            return AjaxCallbackMessage('项目图片删除成功', true, url('project/photo?id=' . $photo->project_id));
        } else {
//            $this->tip('项目图片删除失败', url('project/photo?id=' . $photo['project_id']), false);
            return AjaxCallbackMessage('项目图片删除失败', false);
        }
    }

    /**
     * 查看项目浏览者
     *
     * @return Response
     */
    public function getViewer(Request $request)
    {

        $project_id = $request->input('id');
        $project = Project::find($project_id);
        $viewers = $project->viewer()->with('user')->paginate(10);

        $data = array(
            'project_id' => $project_id,
            'project'    => $project,
            'viewers'    => $viewers,
        );

        return view('project/viewer/index', $data);
    }

    /**
     * 执行一个用户模糊搜索
     */
    public function postUserSearch(Request $request)
    {
        $data = $request->input();

        if ($data['user_search'] == '') {
            return AjaxCallbackMessage('你未输入内容，无法进行模糊搜索', false);
        }

        if (is_numeric(trim($data['user_search']))) {
            $result = User::where('username', 'like', '%' . trim($data['user_search']) . '%')->get();
        } else {
            $result = User::where('realname', 'like', '%' . trim($data['user_search']) . '%')->get();
        }

        if (count($result)) {
            return AjaxCallbackMessage($result, true);
        } else {
            return AjaxCallbackMessage('没有搜索到与你输入内容能匹配的用户', false);
        }
    }

    /**
     * 执行一个用户模糊搜索
     */
    public function postSearchUser(Request $request)
    {
        $data = $request->input();

        $result = User::with('userInfo')->where('uid', $data['uid'])->first();

        if (count($result)) {
            return AjaxCallbackMessage($result, true);
        } else {
            return AjaxCallbackMessage('没有搜索到与你输入内容能匹配的用户', false);
        }
    }

    /**
     * 异步调用getImage()函数
     */
    public function postImage(Request $request)
    {
        $data = $request->input();
        $result = getImage($data['avatar']);

        return AjaxCallbackMessage($result, true);
    }


    /**
     * 删除文件商业计划书
     */
    public function postDeleteFile(Request $request)
    {
        $data = $request->input();
        $file = Attachment::where('filename', htmlspecialchars($data['bp_name']))->first();
        if(!is_object($file)){
            return AjaxCallbackMessage('该文件不存在,或者数据还未关联', false);
        }else{
            $uploadDir = config('upload.uploadDir');
            $explode = explode('/',$file->url);
            array_splice($explode, 3, 0, '_thumb');
            $thumb = implode('/', $explode);
            array_splice($explode, 3, 1, '_large');
            $large = implode('/', $explode);
            $n_result = @unlink($uploadDir.substr($file->url,8));
            $t_result = @unlink($uploadDir.substr($thumb,8).'\_thumb');
            $l_result = @unlink($uploadDir.substr($large,8).'\_thumb');
            Attachment::where('filename', htmlspecialchars($data['bp_name']))->delete();
            Project::where('id', $data['id'])->update(['business_plan'=>0]);
            if(true == $n_result || true==$t_result ||true==$l_result){
                return AjaxCallbackMessage('删除成功', true);
            }else{
                return AjaxCallbackMessage('删除失败，该文件有可能不存在', false);
            }
        }
    }
}
